package com.example.lg.aliplaydemo470.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.aliyun.player.IPlayer;
import com.aliyun.player.nativeclass.PlayerConfig;
import com.aliyun.player.source.UrlSource;
import com.aliyun.vodplayerview.constants.PlayParameter;
import com.aliyun.vodplayerview.widget.AliyunVodPlayerView;
import com.example.lg.aliplaydemo470.view.CustomNestedScrollView;
import com.example.lg.aliplaydemo470.R;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 滑动实现小屏幕播放
 */
public class SmallScreenActivity extends AppCompatActivity {
    private static final String TAG = "SmallScreenActivity";
    @BindView(R.id.btn_play)
    Button btnPlay;
    @BindView(R.id.linear_layout)
    LinearLayout mLinearLayout;
    @BindView(R.id.nestedscrollview)
    CustomNestedScrollView mNestedScrollView;
    @BindView(R.id.frame_layout)
    FrameLayout mFrameLayout;

    private AliyunVodPlayerView mAliyunVodPlayerView;
    private View mView;
    private FrameLayout.LayoutParams layoutParams;
    private FrameLayout.LayoutParams layoutParamsSmallVideo;
    private boolean isSmallVideoDisplay = false;

    private int videoPlayHeight;
    private int smallVideoHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_small_screen);
        ButterKnife.bind(this);

        videoPlayHeight = dip2px(this, 200);
        smallVideoHeight = dip2px(this, 150);
        initAliyunPlayerView();
        playVideo();//播放视频

        initEvent();
    }

    private void initEvent() {

        mNestedScrollView.addOnScrollChangedListener(new CustomNestedScrollView.OnScrollChangedListener() {
            @Override
            public void scrollChangedListener(int y) {
                if (y >= videoPlayHeight) {//顶部播放器不可见了
                    if (!isSmallVideoDisplay) {

                        isSmallVideoDisplay = true;
                        mAliyunVodPlayerView.setControlBarCanShow(false);
                        mLinearLayout.post(new Runnable() {
                            @Override
                            public void run() {
                                mLinearLayout.removeView(mAliyunVodPlayerView);
                                mLinearLayout.addView(mView, 0, new FrameLayout.LayoutParams(0, videoPlayHeight));

                                layoutParamsSmallVideo = new FrameLayout.LayoutParams(smallVideoHeight, smallVideoHeight);
                                layoutParamsSmallVideo.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
                                layoutParamsSmallVideo.rightMargin = 20;
                                mFrameLayout.addView(mAliyunVodPlayerView, layoutParamsSmallVideo);

                            }
                        });
                    }
                } else {
                    if (isSmallVideoDisplay) {
                        isSmallVideoDisplay = false;
                        mAliyunVodPlayerView.setControlBarCanShow(true);
                        mFrameLayout.post(new Runnable() {
                            @Override
                            public void run() {
                                mFrameLayout.removeView(mAliyunVodPlayerView);

                                mLinearLayout.removeView(mView);
                                mLinearLayout.addView(mAliyunVodPlayerView, 0, layoutParams);
                            }
                        });
                    }
                }
            }
        });

        //以下为几个常用监听回调
        mAliyunVodPlayerView.setOnPlayStateBtnClickListener(new AliyunVodPlayerView.OnPlayStateBtnClickListener() {
            @Override
            public void onPlayBtnClick(int playerState) {
                if (playerState == IPlayer.started) {
                    Log.i(TAG, "onPlayBtnClick: 暂停");
                } else if (playerState == IPlayer.paused) {
                    Log.i(TAG, "onPlayBtnClick: 播放");
                } else {
                    Log.i(TAG, "onPlayBtnClick: else");
                }
            }
        });

        mAliyunVodPlayerView.setOnCompletionListener(new IPlayer.OnCompletionListener() {
            @Override
            public void onCompletion() {
                Log.i(TAG, "onCompletion:  视频正常播放完成");
            }
        });
        mAliyunVodPlayerView.setOnFirstFrameStartListener(new IPlayer.OnRenderingStartListener() {
            @Override
            public void onRenderingStart() {
                Log.i(TAG, "onRenderingStart: 视频第一帧开始");
            }
        });


        //网络连接监听
        mAliyunVodPlayerView.setNetConnectedListener(new AliyunVodPlayerView.NetConnectedListener() {
            @Override
            public void onReNetConnected(boolean isReconnect) {

            }

            @Override
            public void onNetUnConnected() {

            }
        });


    }

    private void playVideo() {


        UrlSource urlSource = new UrlSource();
        urlSource.setCoverPath("http://image.test.laodao.so/image/course/course/5cf047c0-ba7d-11e9-b949-23e7199f12a0.jpg");
        urlSource.setTitle("小窗口视频测试");
        urlSource.setUri(PlayParameter.PLAY_PARAM_URL);

        PlayerConfig playerConfig = mAliyunVodPlayerView.getPlayerConfig();
        //默认是5000
        int maxDelayTime = 5000;
        if (PlayParameter.PLAY_PARAM_URL.startsWith("artp")) {
            //如果url的开头是artp，将直播延迟设置成100，
            maxDelayTime = 100;
        }
        playerConfig.mMaxDelayTime = maxDelayTime;
        mAliyunVodPlayerView.setPlayerConfig(playerConfig);
        mAliyunVodPlayerView.setLocalSource(urlSource);
    }

    private void initAliyunPlayerView() {


        String sdDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test_save_cache";
        File file = new File(sdDir);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
        }


        mAliyunVodPlayerView = new AliyunVodPlayerView(this);
        mView = new View(this);

        //保持屏幕敞亮
        mAliyunVodPlayerView.setKeepScreenOn(true);
        mAliyunVodPlayerView.setPlayingCache(true, sdDir, 60 * 60 /*时长, s */, 300 /*大小，MB*/);
        mAliyunVodPlayerView.setTheme(AliyunVodPlayerView.Theme.Green);
        mAliyunVodPlayerView.setCirclePlay(false);//是否循环播放
        mAliyunVodPlayerView.setAutoPlay(true);//是否自动播放
        mAliyunVodPlayerView.setTitleBarCanShow(false);
        //mAliyunVodPlayerView.setRenderRotate(IPlayer.RotateMode.ROTATE_90);


        layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, videoPlayHeight);
        mLinearLayout.addView(mAliyunVodPlayerView, 0, layoutParams);


    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.setAutoPlay(true);
            mAliyunVodPlayerView.onResume();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.setAutoPlay(false);
            mAliyunVodPlayerView.onStop();
        }
    }

}
